package com.achilles.learnhandlethread;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    private HandlerThread mHandlerThread;
    private Handler mHandlerNotInMainThread;
    private Handler mHandlerInMainThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mHandlerThread = new HandlerThread("HandleThread");
        mHandlerThread.start();     //此句必须在mHandlerThread.getLooper()前调用
        mHandlerNotInMainThread = new Handler(mHandlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Bundle bundle = msg.getData();
                int number = bundle.getInt("Number");
                Log.i("AchillesL", String.valueOf(number) + " in Thread: " + Thread.currentThread
                        ().getName());
            }
        };

        mHandlerInMainThread = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Bundle bundle = msg.getData();
                int number = bundle.getInt("Number");
                Log.i("AchillesL", String.valueOf(number) + " in Thread: " + Thread.currentThread
                        ().getName());
            }
        };
        MyThread myThread = new MyThread();
        myThread.start();
    }

    class MyThread extends Thread {
        @Override
        public void run() {
            super.run();
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(500);

                    //此处一个Message只能赋值给一个Thread
                    Message messageUI = Message.obtain();
                    Message messageThread = Message.obtain();

                    Bundle bundle = new Bundle();
                    bundle.putInt("Number", i);
                    messageUI.setData(bundle);
                    messageThread.setData(bundle);

                    mHandlerNotInMainThread.sendMessage(messageThread);
                    mHandlerInMainThread.sendMessage(messageUI);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
